/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.fatecpg.songs.dao.hibernate;


import br.com.fatecpg.songs.dao.util.HibernateSession;
import br.com.fatecpg.songs.entity.Persistent;
import java.io.Serializable;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.criterion.Order;

/**
 *
 * @param <E> 
 * @author Marcos Costa
 */
public class GenericDAO<E extends Persistent> implements br.com.fatecpg.songs.dao.GenericDAO<E>{
    protected Class<? extends Persistent> clazz;
    
    /**
     *
     * @param clazz
     */
    public GenericDAO(Class<? extends Persistent> clazz) {
        this.clazz = clazz;
    }
                
    /**
     *
     * @param id
     * @return
     */
    @Override
    public E load(Serializable id){
        Session session = HibernateSession.currentSession();
        E object= (E) session.load(clazz, id);
        return object;
    }
    
    /**
     *
     * @param persistent
     */
    @Override
    public void save(E persistent){        
        Session session = HibernateSession.currentSession();
        session.persist(persistent);            
    }
    
    /**
     *
     * @param persistent
     */
    @Override
    public void update(E persistent){
        Session session = HibernateSession.currentSession();
        session.merge(persistent);             
    }
    
    /**
     *
     * @param persistent
     */
    @Override
    public void delete(E persistent){
        Session session = HibernateSession.currentSession();        
        HibernateSession.currentSession().flush();
        session.delete(persistent);         
    }
    
    /**
     *
     * @return
     */
    @Override
    public List<E> list(){
        Session session = HibernateSession.currentSession();
        List<E> list = session.createCriteria(clazz).addOrder(Order.asc("id")).list();                   
        return list;
    }              

}
